<template>
   <!-- 概况及管理目标 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel == 0 ? {} : rules"
      :class="editModel == 0?'':'rulesForm'"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="概况及管理目标"></title-name>
          <span class="scene">现场条件</span>
          <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
          </custom-form>
        </a-card>
      </a-spin>
    </a-form-model>
     
</template>

<script>
import { updateByEntity,getPlanOverviewAndManagementObjectivesById} from '@/api/projectManagementPlanning/managementObjective'
import { getProjectsDel } from '@/api/project/projects'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import { investmentData,contractingModeData,institutionalData,contractPriceData,qualityObjectivesData,cTargetData} from './model'
import moment from 'moment'
export default {
  name:'managementObjective' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BSelect,
  },
   props: {
    // 表单
    baseFormInfo: {
      type: Object,
      default: () => {}
    },
    },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 0, // 操作状态:0 查看;1 编辑
      projectOrgId:null,
      form: {totalConstructionPeriod:null}, // 表单
      id: '',
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      rules: {
        constructionUnitName: [{ required: true,message: '请输入建设单位名称', trigger: 'blur' }],
        designerUnitName: [{ required: true,message: '请输入设计单位名称', trigger: 'blur' }],
        natureInvestment: [{ required: true, message: '请选择投资性质', trigger: 'change' }],
        otherNatureInvestment: [{ required: true,message: '请输入其他投资性质', trigger: 'blur' }],
        projectType: [{ required: true,message: '请输入工程类别', trigger: 'blur' }],
        totalProjectPrice: [{ required: true,message: '请输入暂估工程总价(元)', trigger: 'blur' }],
        contractingMode: [{ required: true, message: '请选择承包模式', trigger: 'change' }],
        projectOrganizationForm: [{ required: true, message: '请选择项目组织机构形式', trigger: 'change' }],
        contractPriceType: [{ required: true, message: '请选择合同价格类型', trigger: 'change' }],
        projectAddr: [{ required: true,message: '请输入工程地点', trigger: 'blur' }],
        projectScale: [{ required: true,message: '请输入项目规模', trigger: 'blur' }],
        contractWorkContent: [{ required: true,message: '请输入合同工作内容/范围简述', trigger: 'blur' }],
        contractualStipulation: [{ required: true,message: '请输入质量目标(合同约定)', trigger: 'blur' }],
        qualifiedRate: [{ required: true,message: '请输入质量一次交验合格率（%）', trigger: 'blur' }],
        otherQualityObjectives: [{ required: true,message: '请输入其他质量目标', trigger: 'blur' }],
        desginGoal: [{ required: true,message: '请输入设计目标', trigger: 'blur' }],
        planStartTime: [{ required: true, message: '请选择计划开工日期', trigger: 'change' }],
        planEndTime: [{ required: true, message: '请选择计划竣工日期', trigger: 'change' }],
        safetyObjectives: [{ required: true,message: '请输入安全目标（含创优目标、事故控制目标）', trigger: 'blur' }],
        greenConstructionGoal: [{ required: true,message: '请输入绿色建造目标', trigger: 'blur' }],
        outputEnergyConsumption: [{ required: true,message: '请输入万元产值能耗（吨标准煤/万元）', trigger: 'blur' }],
        costTarget: [{ required: true,message: '请输入', trigger: 'blur' }],
        collectionProcess: [{ required: true,message: '请输入', trigger: 'blur' }],
        collectionSubject: [{ required: true,message: '请输入', trigger: 'blur' }],
        collectionCompleted: [{ required: true,message: '请输入', trigger: 'blur' }],
        collectionSettlement: [{ required: true,message: '请输入', trigger: 'blur' }],
        planAchievements: [{ required: true,message: '请输入计划完成科技成果（项）', trigger: 'blur' }],
        scienceAndTechnologyAward: [{ required: true,message: '请输入科学技术奖（级别）', trigger: 'blur' }],
        c1: [{ required: true,message: '请输入C1目标', trigger: 'blur' }],
        projectManagementResults: [{ required: true,message: '请输入项目管理成果', trigger: 'blur' }],

      }, // 校验规则
      init: false, // 初始化控件
    }
  },
  created() {},
  async mounted() {
  this.getDetailData();
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'constructionUnitName',
          type: 'a-input',
          disabled: this.editModel == 0,
          label: '建设单位名称',
          placeholder: '带出可修改',
        },
        {
          keyName: 'designerUnitName',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '设计单位名称',
          placeholder: '带出可修改',
          attrs: {
              maxLength : 30,
          },
        },
        {
          keyName: 'natureInvestment',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '投资性质',
          data: investmentData,
        },
        {
          keyName: 'otherNatureInvestment',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          formClass:'otherNatureInvestmentOne',
          hidden: (this.form.natureInvestment && this.form.natureInvestment*1===6)?false:true,
          label: '其他投资性质',
          attrs: {
              maxLength : 30,
          },
        },
        {
          keyName: 'projectType',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '工程类别',
          attrs: {
              maxLength : 30,
          },
        },
         {
          keyName: 'totalProjectPrice',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          label: '暂估工程总价(元)',
          precision:2,
           attrs: {
              min:0.01,
          },
        },
        {
          keyName: 'contractingMode',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '承包模式',
          data: contractingModeData,
        },
        {
          keyName: 'projectOrganizationForm',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '项目组织机构形式',
          data: institutionalData,
        },
        {
          keyName: 'contractPriceType',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '合同价格类型',
          data: contractPriceData,
        },
        {
          keyName: 'projectAddr',
          type: 'a-input',
          disabled: this.editModel == 0,
          label: '工程地点',
          placeholder: '带出项目立项信息中的“项目地点”，可修改',
          span:24
        },
        {
          keyName: 'projectScale',
          type: 'BaseTextarea',
          label: '项目规模',
          disabled: this.editModel == 0,
          span: 24
        },
          {
          keyName: 'contractWorkContent',
          type: 'BaseTextarea',
          label: '合同工作内容/范围简述',
          disabled: this.editModel == 0,
          span: 24
        },
         {
          keyName: 'contractualStipulation',
          type: 'a-select',
          formClass:'contractualStipulation',
          disabled: this.editModel == 0,
          label: '质量目标(合同约定)',
          data: qualityObjectivesData,
        },
        {
          keyName: 'qualifiedRate',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          formClass:'otherNatureInvestment',
          label: '质量一次交验合格率（%）',
          hidden: (this.form.contractualStipulation && this.form.contractualStipulation*1===3)?false:true,
          precision:2,
          attrs: {
              min:0.01,
          },
        },
        {
          keyName: 'otherQualityObjectives',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          formClass:'marginTop',
          formClass:'otherNatureInvestment',
          hidden: (this.form.contractualStipulation && this.form.contractualStipulation*1===4)?false:true,
          label: '其他质量目标',
           attrs: {
              maxLength : 30,
          },
        },
        {
          keyName: 'desginGoal',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '设计目标',
          span: 24
        },
        {
          keyName: 'planStartTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '计划开工日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: this.disableStarDate
          }
        },
        {
          keyName: 'planEndTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '计划竣工日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD',
             disabledDate: this.disabledDate
          },
        },
        {
          keyName: 'totalConstructionPeriod',
          type: 'a-input',
          disabled: true,
          label: '总工期（天）',
          placeholder: '计划竣工日期-计划开工日期',
        },
         {
          keyName: 'sectionDuration',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          formClass:'sectionTime',
          label: '区段工期（如果有）',
          span:24
        },
        {
          keyName: 'safetyObjectives',
          type: 'BaseTextarea',
          label: '安全目标（含创优目标、事故控制目标）',
          disabled: this.editModel == 0,
          span: 24
        },
        {
          keyName: 'greenConstructionGoal',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '绿色建造目标',
           attrs: {
              maxLength : 30,
          },
        },
        {
          keyName: 'outputEnergyConsumption',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          label: '万元产值能耗（吨标准煤/万元）',
          precision:2,
           attrs: {
              min:0.01,
          },
        },
        {
          keyName: 'costTarget',
          type: 'a-input-number',
          disabled: this.editModel == 0,
          label: '成本目标（%）（目标责任书指标）',
          precision:2,
           attrs: {
              min:0.01,
          },
        },
        {
          keyName: 'collectionProcess',
          type: 'a-input-number',
          formClass:'collectionTarget',
          disabled: this.editModel == 0,
          placeholder: '请输入',
          label: '收款目标：  按照合同约定比例按时足额回收工程款，过程',
          precision:2,
          attrs: {
              min:0.01,
          },
          span:12
        },
         {
          keyName: 'collectionSubject',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          formClass:'mainbBody',
          label: '%，主体',
          precision:2,
          attrs: {
              min:0.01,
          },
          span:4
        },
        {
          keyName: 'collectionCompleted',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          formClass:'mainbBody',
          label: '%，竣工',
          precision:2,
          attrs: {
              min:0.01,
          },
          span:4
        },
        {
          keyName: 'collectionSettlement',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          formClass:'settlement',
          label: '%，结算完',
          precision:2,
          attrs: {
              min:0.01,
          },
          span:4
        },
        {
          keyName: 'planAchievements',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          label: '计划完成科技成果（项）',
          precision:0,
          attrs: {
              min:1,
          },
        },
         {
          keyName: 'scienceAndTechnologyAward',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '科学技术奖（级别）',
           attrs: {
              maxLength : 30,
          },
        },
        {
          keyName: 'c1',
          disabled: this.editModel == 0,
          type: 'a-select',
          label: 'C1目标',
          data: cTargetData,
        },
         {
          keyName: 'projectManagementResults',
          type: 'BaseTextarea',
          label: '项目管理成果',
          disabled: this.editModel == 0,
          span: 24
        },
        {
          keyName: 'otherObjectives',
          type: 'BaseTextarea',
          label: '其他目标',
          disabled: this.editModel == 0,
          span: 24
        },
      ]
    },
  },
  watch: {
    'baseFormInfo':{
        handler (val, oldVal) {
          this.projectOrgId =val.projectId;
          this.editModel>0 && this.getgetProjectsDetail(this.projectOrgId);  //查看不用调用
    },
    deep: true
  },
    // 监听开工日期
  'form.planStartTime'(val) {
      if(val && this.form.planStartTime){
         let flag = this.compareDate(val,this.form.planEndTime)
          if(flag){
            this.$set(this.form,'planEndTime',null)
            this.$set(this.form,'totalConstructionPeriod',null)
          }
      }
      if(val && this.form.planEndTime){
        this.setTotalConstructionPeriod();
      }
    },
   'form.planEndTime'(val) {
      if(val && this.form.planStartTime){
         this.setTotalConstructionPeriod();
      }
    },
  },

  methods: {
  compareDate(date1,date2){   //比较两个日期大小
    let flag,
    oDate1 = new Date(date1),
    oDate2 = new Date(date2);
    if(oDate1.getTime() > oDate2.getTime()){
        flag = true
    } else {
      flag = false
    }
    return flag;
  },
    getgetProjectsDetail(value){
      getProjectsDel({ projectId: value }).then(res => {
      // if()
     !this.form.constructionUnitName && this.$set(this.form,'constructionUnitName',res.data.constructionName)
     !this.form.designerUnitName && this.$set(this.form,'designerUnitName',res.data.designUnitName)
     !this.form.projectAddr && this.$set(this.form,'projectAddr',res.data.projectAddress)
    })
    },
    DateMinus(date1,date2){//date1:小日期   date2:大日期
       let sdate = new Date(date1),
   　　now = new Date(date2),
   　　days = now.getTime() - sdate.getTime(),
   　　day = parseInt(days / (1000 * 60 * 60 * 24)) + 1;
   　　return day;
   },
   setTotalConstructionPeriod(){
     let totalConstructionPeriod = this.DateMinus(this.form.planStartTime,this.form.planEndTime)
     this.$set(this.form,'totalConstructionPeriod',totalConstructionPeriod)
   },
     disabledDate(current) {
      if (this.form.planStartTime) {
        let planStartTime;
        if (typeof this.form.planStartTime === 'string') {
          planStartTime = moment(this.form.planStartTime)
        } else {
          planStartTime = this.form.planStartTime
        }
        return current && current < moment(this.form.planStartTime)
      }
      return true
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
      return flag
    },
    cleanNull(obj) {
      for (let propName in obj) {
        if (obj[propName] === null) {
          delete obj[propName];
        }
      }
    },
    getDetailData() {
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        let reqObj = {
          planId: this.id
        }
        if(this.version){
         reqObj.version = this.version;
        }
        getPlanOverviewAndManagementObjectivesById(reqObj)
          .then((res) => {
            this.loading = false
            this.form = { ...this.form, ...res.data }
            this.cleanNull(this.form )
            this.form
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      }
    },
    sure(str){
      let that = this;
      this.$confirm({
        okText: '确认',
        okType: 'warning',
        cancelText: '取消',
        title: '提交?',
        content: `请确认是否要提交?`,
        onOk() {
            that.saveFn(str);
        },
        onCancel() {
        },
      })
    },
    /**
     * 提交表单
     */
   managementObjectiveSubmit(formBase) {  //保存
      if (!this.validateForm()) {
        return
      }
      this.sure(2);
    },
    managementObjectiveSaveDrafts(formBase) {  //保存草稿
        this.saveFn(1);

    },
   saveFn(status){
      this.loading = true
      let form = this.$clone(this.form)
       let msg = status*1===2?"提交":"保存草稿";
      form.auditStatus = status;
      // form.isChange = 0;  //先写死
      form.isChange = this.pageType=='change'?1:0;  // 是编辑还是变更
      let api = updateByEntity;
      api(form)
        .then(() => {
          this.loading = false
          this.$message.success(`${msg}成功！`);
          this.$multiTab.close()
        })
        .catch(() => {
          this.loading = false
          this.$message.warning(err.data.message)
        })
   }

  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
 .scene{
     display: block;
     margin: 10px 0 10px 60px;
     color: rgba(0, 0, 0, 0.85);
 }
 .rulesForm{
   @{deep} .otherNatureInvestmentOne .ant-input{
     border-color: #e4ac0b;
     background-color: #FFF9E8;
   }
   @{deep} .otherNatureInvestment .ant-input-number-input,   @{deep} .otherNatureInvestment .ant-input{
     border-color: #e4ac0b;
     background-color: #FFF9E8;
   }
 }
  @{deep} .otherNatureInvestment{
    margin-top: 30px;
   }
   @{deep} .sectionTime{
      .ant-form-item-label{
       width: 150px;
       margin-left: 5px;
     }
      .ant-form-item-control-wrapper{
        position: relative;
       width: calc(100% - 285px);
         &::after{
             content: '工期履约率100%';
             position: absolute;
             right: -110px;
             top:7px;

        }
      }
   }
   @{deep} .collectionTarget{
     .ant-form-item-label{
       width: 426px;
       margin-left: 5px;
     }
      .ant-form-item-control-wrapper{
       width: calc(100% - 431px);
      }
   }
   @{deep} .contractualStipulation{
     position: relative;
     margin-top: 30px;
      &::before{
             content: '项目总目标';
             position: absolute;
             left: 55px;
             top: -35px;
             color: rgba(0, 0, 0, 0.85);
        }
   }
   @{deep} .mainbBody{
      .ant-form-item-label{
       width: 83px;
       margin-left: 5px;
     }
      .ant-form-item-control-wrapper{
       width: calc(100% - 88px);
      }
   }
   @{deep} .settlement{
      .ant-form-item-label{
       width: 100px;
       margin-left: 5px;
     }
      .ant-form-item-control-wrapper{
        position: relative;
       width: calc(100% - 135px);
       &::after{
             content: '%';
             position: absolute;
             right: -18px;
             top:7px;

        }
       }
   }

</style>
